package com.qf.fengmimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fengmimall.ex.UserException;
import com.qf.fengmimall.product.entity.Product;
import com.qf.fengmimall.product.entity.ProductSku;
import com.qf.fengmimall.product.entity.ShoppingCart;
import com.qf.fengmimall.product.mapper.ProductMapper;
import com.qf.fengmimall.product.mapper.ShoppingCartMapper;
import com.qf.fengmimall.product.service.IProductSkuService;
import com.qf.fengmimall.product.service.IShoppingCartService;
import com.qf.fengmimall.vo.ShopCartVo;
import com.qf.fengmimall.vo.ShoppingCartVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车  服务实现类
 * </p>
 *
 * @author lx
 * @since 2023-02-16
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private IProductSkuService productSkuService;

    /**
     * 添加购物车
     *
     * @param shopCartVo
     * @throws UserException
     */
    @Transactional(rollbackFor = UserException.class)
    @Override
    public void insertShoppingCart(ShopCartVo shopCartVo) throws UserException {
        ShoppingCart shoppingCart = new ShoppingCart();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        shoppingCart.setCartTime(simpleDateFormat.format(new Date()));
        BeanUtils.copyProperties(shopCartVo, shoppingCart);
        boolean save = save(shoppingCart);
        if (!save) {
            throw new UserException(10001, "添加购物车失败");
        }
    }

    /**
     * 查看购物车列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingCartVo> shoppingCartList(String userId) {
        //通过用户id查询购物车信息
        List<ShoppingCart> shoppingCartList = list(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, userId));
        List<ShoppingCartVo> shoppingCartVos = getShoppingCartVos(shoppingCartList);
        return shoppingCartVos;
    }

    /**
     * 组装ShoppingCartVo
     * @param shoppingCartList
     * @return
     */
    private List<ShoppingCartVo> getShoppingCartVos(List<ShoppingCart> shoppingCartList) {
        //获取购物车中商品id
        List<String> productIds = shoppingCartList.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());

        //根据productIds 获取商品信息
        List<Product> products = productMapper.getProductImgsBuyIds(productIds);

        //获取productId与product对应关系
        Map<String, Product> productMap = products.stream().collect(Collectors.toMap(Product::getProductId, o -> o));

        //获取购物车中product_skuid
        List<String> productSkuIds = shoppingCartList.stream().map(ShoppingCart::getSkuId).collect(Collectors.toList());
        //更具product_skuid查询商品包装信息
        List<ProductSku> productSkus = productSkuService.list(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getSkuId, productSkuIds));
        //获取productskuid与productsku对应关心
        Map<String, ProductSku> productSkuMap = productSkus.stream().collect(Collectors.toMap(ProductSku::getSkuId, o -> o));

        List<ShoppingCartVo> shoppingCartVos = new ArrayList<>();

        for (ShoppingCart shoppingCart : shoppingCartList) {
            ShoppingCartVo shoppingCartVo = new ShoppingCartVo();
            BeanUtils.copyProperties(shoppingCart, shoppingCartVo);
            shoppingCartVos.add(shoppingCartVo);
        }


        //遍历购物车组装vo
        for (ShoppingCartVo shoppingCartVo : shoppingCartVos) {
            String productId = shoppingCartVo.getProductId();
            Product product = productMap.get(productId);
            shoppingCartVo.setProductName(product.getProductName());
            shoppingCartVo.setProductImg(product.getImgs().get(0).getUrl());
            String skuId = shoppingCartVo.getSkuId();
            ProductSku productSku = productSkuMap.get(skuId);
            shoppingCartVo.setSkuName(productSku.getSkuName());
            shoppingCartVo.setOriginalPrice(productSku.getOriginalPrice());
            shoppingCartVo.setSellPrice(productSku.getSellPrice());
            shoppingCartVo.setStock(productSku.getStock());
        }
        return shoppingCartVos;
    }

    /**
     * 更改购物车数量
     *
     * @param id
     * @param num
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateShoppCart(Integer id, String num) {
        UpdateWrapper<ShoppingCart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("cart_num", num);
        updateWrapper.eq("cart_id", id);
        update(updateWrapper);
    }

    /**
     * 更具购物车id查询
     *
     * @param cids
     * @return
     */
    @Override
    public List<ShoppingCartVo> listByCids(String cids) {
        String[] cid = cids.split(",");
        List<String> cidList = Arrays.asList(cid);
        List<ShoppingCart> shoppingCarts = list(new QueryWrapper<ShoppingCart>().in("cart_id", cidList));
        List<ShoppingCartVo> shoppingCartVos = getShoppingCartVos(shoppingCarts);
        return shoppingCartVos;
    }
}
